package com.yi.gostockgo.service.httpApi;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author ：liandyao
 * @description：专门用于取接口数据
 * @date ：2020/4/27 16:18
 */
public class OkHttpService {

    static Logger logger = LoggerFactory.getLogger(OkHttpService.class);

    static int count = 0 ;

    /**
     * 几秒刷新
     */
    public static int second = 6000 ;

    /**
     * 如需简单数据请在id前面加上s_
     * 例如,s_sh000001,如果需要详细数据使用sh000001
     */


    /**
     *大盘指数
     */
    public static final String API_URL = "http://hq.sinajs.cn/list=";

    /**
     * 上证A涨幅
     */
    public static final String SH_UP = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=changepercent&asc=0&node=sh_a&symbol=&_s_r_a=init";

    /**
     * 深圳A涨幅
     */
    public static final String SZ_UP = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=changepercent&asc=0&node=sz_a&symbol=&_s_r_a=init";


    /**
     * 创业板涨幅
     */
    public static final String CY_UP ="http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=changepercent&asc=0&node=cyb&symbol=&_s_r_a=sort";

    /**
     * 简易-上证指数
     */
    public static final String S_SH = "s_sh000001";

    /**
     * 上证指数
     */
    public static final String SH = "sh000001";

    /**
     * 简易-深成指数
     */
    public static final String S_SC = "s_sz399001";

    /**
     * 深成指数
     */
    public static final String SC = "sz399001";

    /**
     * 创业板指
     */
    public static final String CY = "sz399006";

    /**
     * 简易-创业板指
     */
    public static final String S_CY = "s_sz399006";


    /**
     * 指数数据
     */
    private static Map<String,Object> mapType = null;

    /**
     * 涨幅数据
     */
    private static Map<String,Object> mapUp = null;




    //确保该方法只执行一次
    static{

        mapType = new HashMap<>();
        mapUp = new HashMap<>() ;

        //执行任务,每秒执行一次
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

                //上海指数
                StockType sh = getStockType(S_SH);
                StockType sc = getStockType(S_SC);
                StockType cy = getStockType(S_CY);

                mapType.put(SH,sh);
                mapType.put(SC,sc);
                mapType.put(CY,cy);


                logger.info(+count+":"+JSON.toJSONString(mapType));
            }
        };

        //每秒执行一次
        timer.schedule(task,1000,second);


        //每小时执行一次排行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //涨幅排名
                mapUp.put("sh_a",upSort("sh")); //上证A涨幅排名前40
                mapUp.put("sz_a",upSort("sz")); //深圳A
                mapUp.put("cy_a",upSort("cy")); //创业涨幅

                logger.info("排行数据:"+JSON.toJSONString(mapUp));

            }
        },1000,1000*60*60);


    }

    /**
     * 找到所有的指数数据接口
     * @return
     */
    public static Map<String,Object> findStockType()  {

        return mapType ;
    }

    /**
     * 找到所有的指数排名
     * @return
     */
    public static Map<String,Object> findStockUp()  {

        return mapUp ;
    }



    /**
     * 得到相应的指数
     * @param id
     * @return
     */
    private static StockType getStockType(String id){
        count++;
        HTTP http = HTTP.builder().build();
        //String sh = http.async(API_URL+id).get().getResult().getBody().toString();

        HttpResult result =  http.async(API_URL+id).get().getResult() ;

        //如果收到响应
        if(result.getState()== HttpResult.State.RESPONSED){
            String sh = result.getBody().toString();
            String shArr[]=sh.split("=")[1].replaceAll("\"","").split(",");

            StockType shType = new StockType(id,shArr[0],shArr[1],shArr[2],shArr[3],shArr[4],shArr[5]);

            return shType;
        }

        return new StockType();


    }


    /**
     * 涨幅排名
     * @param type sh , sz ,cy
     * @return
     */
    private static List<Stock> upSort(String type){
        String url = "" ;
        if("sh".equals(type)){
            url = SH_UP ;
        }else if("sz".equals(type)){
            url = SZ_UP ;
        }else if("cy".equals(type)){
            url = CY_UP ;
        }
        List<Stock> list = new ArrayList<>();

        HTTP http = HTTP.builder().build();
        HttpResult result =  http.async(url).get().getResult() ;

        //如果收到响应
        if(result.getState()== HttpResult.State.RESPONSED){
            //String body = result.getBody().toString();
            //logger.info();
            //JSONArray arr = result.getBody().toJsonArray();
            list = result.getBody().toList(Stock.class);
            logger.info("抓取的数据有:"+list.size());
            /*for(int i=0;i<arr.size();i++) {

                Stock stock=arr.getObject(i,Stock.class);
                list.add(stock);

            }*/
        }

        return list ;


    }








}
